from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from core.models import UserProfile, Subject, TermDatabase, Word, UserCollection
import random

class Command(BaseCommand):
    help = '创建一个新用户，随机等级，随机专业领域，随机收藏，本专业的随机术语'

    def handle(self, *args, **options):
        # 假设 LEVEL_CHOICES 定义在某个模型中
        try:
            from core.models import LEVEL_CHOICES
        except ImportError:
            LEVEL_CHOICES = [(i, str(i)) for i in range(1, 6)]  # 示例等级范围 1 - 5

        # 创建新用户
        username = f'random_user_{random.randint(1000, 9999)}'
        email = f'{username}@example.com'
        password = 'random_password'
        user = User.objects.create_user(username=username, email=email, password=password)

        # 随机选择等级
        random_level = random.choice(LEVEL_CHOICES)[0]

        # 随机选择专业领域
        subjects = Subject.objects.all()
        if subjects:
            random_subject = random.choice(subjects)
        else:
            self.stdout.write(self.style.ERROR('没有可用的专业领域，请先创建一些专业。'))
            return

        # 创建用户资料
        user_profile, created = UserProfile.objects.get_or_create(user=user)
        user_profile.chinese_level = random_level
        user_profile.subject = random_subject
        user_profile.save()

        # 随机收藏单词
        words = Word.objects.filter(level=random_level)
        if words:
            num_words_to_collect = random.randint(1, 5)
            random_words = random.sample(list(words), min(num_words_to_collect, len(words)))
            for word in random_words:
                UserCollection.objects.get_or_create(user=user, word=word)

        # 随机收藏本专业的术语
        terms = TermDatabase.objects.filter(term_field=random_subject.name)
        if terms:
            num_terms_to_collect = random.randint(1, 5)
            random_terms = random.sample(list(terms), min(num_terms_to_collect, len(terms)))
            for term in random_terms:
                UserCollection.objects.get_or_create(user=user, term=term)

        self.stdout.write(self.style.SUCCESS(f'成功创建用户 {username}，等级: {random_level}，专业领域: {random_subject.name}'))